package com.hd.manager.webSocket;

import lombok.extern.slf4j.Slf4j;

import javax.xml.ws.Endpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
public class EndpointManager {
    // 接入终端数量多可以改用Map
    private static final ConcurrentHashMap<String,DeviceEndpoint> endpointsMap = new ConcurrentHashMap<String, DeviceEndpoint>();

    // 该字典主要用于判断接收的信息是否发自，已经注册的ip 主要使用键，值置空
    private static final ConcurrentHashMap<String,Boolean> ipIndex = new ConcurrentHashMap<>();

    private static Integer OnlineCount = 0;

    public static void addEnpoint(DeviceEndpoint endpoint) {
        if(endpointsMap.containsKey(endpoint.getDeviceId())) {
            endpointsMap.remove(endpoint.getDeviceId());
            endpointsMap.put(endpoint.getDeviceId(), endpoint);
        }else {
            endpointsMap.put(endpoint.getDeviceId(), endpoint);
            ipIndex.put(endpoint.getIpAddr(),true);
            addOnlineCount();
            log.info(endpoint.getDeviceId() + "，ip: "+endpoint.getIpAddr()+"，已上线！");
        }
//        endpointsMap.put(endpoint.getDeviceId(),endpoint);
    }

    public static synchronized void addOnlineCount(){
        OnlineCount++;
    }

    public static synchronized void deleteOnlineCount(){
        OnlineCount--;
    }

    public static Boolean enpointExist(String deviceId){return endpointsMap.containsKey(deviceId);}

    public static DeviceEndpoint getEnpoint(String deviceId){
        return endpointsMap.get(deviceId);
    }

    public static void removeEndpoint(DeviceEndpoint endpoint) {
        endpointsMap.remove(endpoint.getDeviceId());
        deleteOnlineCount();
        log.info(endpoint.getDeviceId() + "，ip: "+endpoint.getIpAddr()+"已下线！");
    }

    public static void broadcast(String message) {
        for (DeviceEndpoint endpoint : endpointsMap.values()) {
            endpoint.sendMessage(message);
        }
    }

    public static void sendMessage(String deviceId, String message) {
        DeviceEndpoint endpoint = endpointsMap.get(deviceId);
        endpoint.sendMessage(message);
    }

    public static Integer getOnlineCount() {
        return OnlineCount;
    }

    public static Boolean ipExist(String ip){
        return ipIndex.containsKey(ip);
    }
}
